package llm

import (
	"context"
	"fmt"

	"github.com/sashabaranov/go-openai"

	"yanxue_ai_go/pkg/common/config"
)

// OpenAIService OpenAI服务
type OpenAIService struct {
	client *openai.Client
	model  string
}

// NewOpenAIService 创建OpenAI服务实例
func NewOpenAIService() (*OpenAIService, error) {
	// 从全局配置中获取OpenAI配置
	openAIConfig := config.GlobalConfig.AI.OpenAI

	// 创建OpenAI客户端
	clientConfig := openai.DefaultConfig(openAIConfig.APIKey)
	if openAIConfig.BaseURL != "" {
		clientConfig.BaseURL = openAIConfig.BaseURL
	}

	client := openai.NewClientWithConfig(clientConfig)

	// 获取模型配置，默认使用gpt-3.5-turbo
	model := openAIConfig.Model
	if model == "" {
		model = "gpt-3.5-turbo"
	}

	return &OpenAIService{
		client: client,
		model:  model,
	}, nil
}

// Ask 执行问答
func (s *OpenAIService) Ask(ctx context.Context, question string) (string, error) {
	// 构造请求
	req := openai.ChatCompletionRequest{
		Model: s.model,
		Messages: []openai.ChatCompletionMessage{
			{
				Role:    openai.ChatMessageRoleUser,
				Content: question,
			},
		},
	}

	// 发送请求
	resp, err := s.client.CreateChatCompletion(ctx, req)
	if err != nil {
		return "", fmt.Errorf("failed to create chat completion: %w", err)
	}

	// 返回回答
	if len(resp.Choices) > 0 {
		return resp.Choices[0].Message.Content, nil
	}

	return "", fmt.Errorf("no response from OpenAI")
}

// GetModel 获取当前使用的模型
func (s *OpenAIService) GetModel() string {
	return s.model
}
